<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'

import apiServe from '@/api'
import { mergeWithKeyExist } from '@/utils'
import { validateMobile } from '@/utils/validate/validate-form'

import BasicDialog from '@/components/Dialog/BasicDialog.vue'

const emit = defineEmits(['on-create', 'on-edit'])

const visible = ref(false)
const loading = ref(false)
let title = ref('创建')

// 显示
const show = (row: Recordable) => {
  visible.value = true
  formRef.value?.clearValidate()
  if (row) {
    title.value = '编辑'
    mergeWithKeyExist(formData, row)
  } else {
    title.value = '创建'
  }
}
// 关闭
const close = () => {
  visible.value = false
  loading.value = false
  Object.assign(formData, initFormData())
}

// 关于 form
const formRef = ref<FormInstance>()
const initFormData = () => ({
  id: '',
  name: '',
  tel: ''
})
const formData = reactive(initFormData())
const rules = reactive<FormRules>({
  name: [
    {
      required: true,
      whitespace: true,
      message: '请输入姓名',
      trigger: 'change'
    }
  ],
  tel: [
    {
      required: true,
      whitespace: true,
      message: '请输入手机号码',
      trigger: 'change'
    },
    { validator: (rule, value, callback) => validateMobile(rule, value, callback), trigger: 'change' }
  ]
})

// 提交
const submit = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      loading.value = true
      const { id, name, tel } = formData
      const params = {
        name: name.trim(),
        tel
      }
      if (formData.id) {
        apiServe.table.editTableItem({
          id,
          ...params
        }).then(() => {
          ElMessage.success('编辑成功')
          emit('on-edit')
          close()
        }).catch(() => {
          loading.value = false
        })
      } else {
        apiServe.table.createTableItem(params).then(() => {
          ElMessage.success('创建成功')
          emit('on-create')
          close()
        }).catch(() => {
          loading.value = false
        })
      }
    }
  })
}

defineExpose({
  show
})
</script>

<template>
  <BasicDialog
    :model-value="visible"
    :loading="loading"
    :title="title"
    @close="close"
    @confirm="submit"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item
        label="姓名"
        prop="name"
      >
        <el-input
          v-model="formData.name"
          placeholder="请输入姓名"
        />
      </el-form-item>
      <el-form-item
        label="手机号码"
        prop="tel"
      >
        <el-input
          v-model="formData.tel"
          placeholder="请输入手机号码"
        />
      </el-form-item>
    </el-form>
  </BasicDialog>
</template>

<style scoped lang="less">
@import "index.less";
</style>
